package dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import modelo.Propaganda;

public class PropagandaDao {
	
	private EntityManagerFactory emf;
	private EntityManager em;
	
	public PropagandaDao(){
		try {
			Class.forName("org.postgresql.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		this.emf = Persistence.createEntityManagerFactory("banco_quero_teto");
		this.em  = emf.createEntityManager();
	}
	
	public boolean cadastrar(Propaganda propaganda){
		em.getTransaction().begin();
		
		try {
			em.persist(propaganda);
			em.getTransaction().commit();
			
			return true;
		} catch (Exception e) {		
			e.printStackTrace();
			return false;
		}
		
	}

	public Propaganda buscar(int id) {
		Propaganda propaganda = em.find(Propaganda.class, id);
		return propaganda;
	}

	public boolean atualizar(Propaganda propaganda){
		em.getTransaction().begin();
		
		try {
			//funcao para fazer o update do propaganda
			em.merge(propaganda);
			em.getTransaction().commit();
			return true;
			
		} catch (Exception e) {
			return false;
		}
		
	}

	/*public List<Propaganda> getLista(){
		Query query = em.createQuery("select i from Propaganda i");
		return (List<Propaganda>)query.getResultList();
	}
	*/
	public List<Propaganda> getLista(){
		Query query = em.createNamedQuery("Propaganda.listaPropaganda");
		return (List<Propaganda>)query.getResultList();
	}
	
	public List<Propaganda> getListaLimtCidade(String cidade){
		Query query = em.createNamedQuery("Propaganda.listaPropagandaLimitCidade");
		query.setParameter("cidade", cidade);
		query.setMaxResults(2);
		return (List<Propaganda>)query.getResultList();
	}
	
	public boolean excluir(int id){
		Propaganda propaganda = buscar(id);
		em.getTransaction().begin();
		em.remove(propaganda);
		em.getTransaction().commit();
		
		return true;
	}
}
